package run.bottle.urp.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import run.bottle.common.entity.AppUser;
import run.bottle.common.exception.UsernameNotFoundException;
import run.bottle.urp.model.po.*;
import run.bottle.urp.repository.*;
import run.bottle.urp.service.RoleService;
import run.bottle.urp.service.UserService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyc
 * @date 2022-03-25
 */
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserRepo userRepo;
    private final RoleRepo roleRepo;
    private final UserRoleRepo userRoleRepo;
    private final RoleService roleService;

    public UserServiceImpl(UserRepo userRepo, RoleRepo roleRepo, UserRoleRepo userRoleRepo, RoleService roleService) {
        this.userRepo = userRepo;
        this.roleRepo = roleRepo;
        this.userRoleRepo = userRoleRepo;
        this.roleService = roleService;
    }

    @Override
    public User findByUsername(String username) {
        return userRepo.findByUsername(username);
    }

    @Override
    public User saveUser(User user) {
        return userRepo.save(user);
    }

    @Override
    public User addRoleToUser(String username, String roleName) {
        User user = userRepo.findByUsername(username);
        Role role = roleRepo.findByRoleName(roleName);
        if (user != null && role != null) {
            UserRole userRole = userRoleRepo.findByUserIdAndRoleId(user.getId(), role.getId());
            if (userRole == null) {
                userRoleRepo.save(new UserRole(null, user.getId(), role.getId()));
            }
        }
        return null;
    }

    @Override
    public AppUser getAppUserByUsername(String username) {
        User user = userRepo.findByUsername(username);
        if (user == null) {
            logger.error("User not found in the database");
            throw new UsernameNotFoundException("此用户不存在");
        } else {
            logger.info("User found in the database:{}", username);
        }
        List<Role> userRoles = roleService.findRoleByUserId(user.getId());

        logger.info("save user info to context");
        AppUser appUser = new AppUser();
        BeanUtils.copyProperties(user, appUser);
        if (!CollectionUtils.isEmpty(userRoles)) {
            List<Long> roleIds = userRoles.stream().map(Role::getId).collect(Collectors.toList());
            appUser.setRoleIds(roleIds);
        }

        return appUser;
    }
}
